﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using org.smslib.modem.athandler;
using System.Threading;
using org.smslib;
using org.smslib.modem;
using System.Text.RegularExpressions;
using org.ajwcc.pduUtils.gsm3040;


namespace SmsUI.SmsCore
{
    public class ATHandler_2583C : ATHandler_Wavecom_Q2438F
    {

        public ATHandler_2583C(ModemGateway myGateway)
            : base(myGateway)
        {
            //this.getTerminators()[1] = "\\s*([\\p{ASCII}]|[^\\x00-\\xff])*\\s+OK\\s";

            //this.getTerminators()[3] = "\\s*([\\p{ASCII}]|[^\\x00-\\xff])*\\s+ERROR\\s";
            //this.getTerminators()[11] = "\\s*\\+CMGS:\\s*\\d+,\\d+";
            this.getTerminators()[1] = "\\s*([\\p{ASCII}]|[^\\x00-\\xff])*\\s+OK\\s";
            setStorageLocations("MT");
        }
        public override bool setTextProtocol()
        {

            //getModemDriver().write("AT+CMEE=1\r");
            //getModemDriver().getResponse();


            getModemDriver().write("AT+CMGF=1\r");
            getModemDriver().getResponse();
            if (getModemDriver().isOk())
            {
                //getModemDriver().write("AT+CSCS=\"CDMA\"\r");
                //getModemDriver().getResponse();
                if (getModemDriver().isOk())
                {
                    getModemDriver().write("AT+WSCL=6,4\r");
                    string s = getModemDriver().getResponse();
                    return true;
                }
                return false;
            }
            return false;
        }
        public override bool setPduProtocol()
        {
            getModemDriver().write("AT+CMGF=1\r");
            getModemDriver().getResponse();
            if (getModemDriver().isOk())
            {
                //getModemDriver().write("AT+CSCS=\"CDMA\"\r");
                //getModemDriver().getResponse();
                if (getModemDriver().isOk())
                {
                    getModemDriver().write("AT+WSCL=6,4\r");
                    string s = getModemDriver().getResponse();
                    return true;
                }
                return false;
            }
            return false;
        }
        public override int sendMessage(int size, string pdu, string phone, string text)
        {
            // text = text + "　";
            //byte[] Bytes = Encoding.BigEndianUnicode.GetBytes(text);
            string testString = "";
            string acString = "";
            char[] sc = new char[] { '！', '＂', '＃', '＄', '％', '＆', '＇', '（', '）', '＊', '＋', '，', '－', '．', '／', '０', '１', '２', '３', '４', '５', '６', '７', '８', '９', '：', '；', '＜', '＝', '＞', '？', '＠', 'Ａ', 'Ｂ', 'Ｃ', 'Ｄ', 'Ｅ', 'Ｆ', 'Ｇ', 'Ｈ', 'Ｉ', 'Ｊ', 'Ｋ', 'Ｌ', 'Ｍ', 'Ｎ', 'Ｏ', 'Ｐ', 'Ｑ', 'Ｒ', 'Ｓ', 'Ｔ', 'Ｕ', 'Ｖ', 'Ｗ', 'Ｘ', 'Ｙ', 'Ｚ', '［', '＼', '］', '＾', '＿', '｀', 'ａ', 'ｂ', 'ｃ', 'ｄ', 'ｅ', 'ｆ', 'ｇ', 'ｈ', 'ｉ', 'ｊ', 'ｋ', 'ｌ', 'ｍ', 'ｎ', 'ｏ', 'ｐ', 'ｑ', 'ｒ', 'ｓ', 'ｔ', 'ｕ', 'ｖ', 'ｗ', 'ｘ', 'ｙ', 'ｚ', '｛', '｜', '｝', '～' };
            char[] dc = new char[] { '!', '\"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~' };
            for (int i = 0; i < sc.Length; i++)
            {
                text = text.Replace(sc[i], dc[i]);
            }

            byte[] Bytes = PduUtils.encodeUcs2UserData(text);
            getModemDriver().write("AT+CMGS=\"" + phone + "\"," + Bytes.Length + "\r");
            Thread.Sleep(20);
            getModemDriver().write(Bytes);
            string cont = Encoding.BigEndianUnicode.GetString(Bytes);

            Thread.Sleep(20);
            //写入CTRL+Z结束短信内容，注意在UNICODE模式下需要两个字节，这个也是不能在超级终端下操作的原因   
            byte[] b2 = new byte[] { 0x00, 0x1a };



            getModemDriver().write(b2);
            int readCount = 0;
            string response = "";

            try
            {
                for (int i = 0; i < 10; i++)
                {
                    response = getModemDriver().getResponse();
                    Thread.Sleep(500);
                    if (response.Contains("CMGS"))
                    {
                        break;
                    }
                    if (response.Contains("ERROR"))
                    {
                        break;
                    }
                }
            }
            catch
            {
            }
            finally
            {

                //Thread.Sleep(3000);
            }

            int refNo = -1;
            if (response.Contains("CMGS") && response.IndexOf("OK\r") >= 0)
            {
                int i;
                StringBuilder tmp = new StringBuilder();
                i = response.IndexOf(":");
                try
                {
                    Regex succ = new Regex("\\s*CMGS: *(\\d+)");



                    if (succ.Match(response).Success)
                    {
                        refNo = 1;

                    }

                }
                catch
                {
                    refNo = -1;
                }
            }
            else refNo = -1;

            return refNo;
        }
        public override bool setIndications()
        {
            getModemDriver().write("AT+CNMI=2,1,0,1,0\r");
            getModemDriver().getResponse();
            return false;
        }
        //public override bool switchStorageLocation(string mem)
        //{
        //    return true;
        //    //return base.switchStorageLocation(mem);
        //}
        public override string getSimStatus()
        {
            return "OK";
        }
        public override string getNetworkRegistration()
        {

            return "AT+CREG=1,1";
        }
        public override void done()
        {
            Console.WriteLine("done");
            //  base.done();
        }
        //public override string getStorageLocations()
        //{
        //    // string s = base.getStorageLocations();
        //    return "OK";
        //}
        //public override bool setVerboseErrors()
        //{
        //    return (getModemDriver().isOk());
        //}
        public override void reset()
        { }
        public override void sync()
        {

        }
        //public override string listMessages(InboundMessage.MessageClasses messageClass)
        //{
        //    string s= base.listMessages(messageClass);
        //    return s;
        //}


        public override string sendCustomATCommand(string atCommand)
        {
            bool re = IsTrueNum(atCommand);
            return re.ToString();
        }
        public bool IsTrueNum(string num)
        {
            string readBuffer;
            bool isSucc = false;
            getModemDriver().write(String.Format("ATD {0};\r", num));
            int atCount = 0;
            while (true)
            {
                atCount++;
                if (atCount > 15)
                {
                    isSucc = false;
                    break;
                }
                System.Threading.Thread.Sleep(1000);
                getModemDriver().write("AT+CLCC\r");
                readBuffer = getModemDriver().getResponse();
                if ((readBuffer.IndexOf("+CLCC: 1,0,3") != -1) || (readBuffer.IndexOf("BUSY") != -1))
                {
                    //一个正振铃的电话或被挂断的电话，号码有效
                    isSucc = true;
                    break;
                }
                else if (readBuffer.IndexOf("+CLCC: 1,0,2") != -1)  //一个正拨打的电话，还未振铃
                {
                    readBuffer = "";
                }
                else if (readBuffer.IndexOf("+CLCC: 1,1,") != -1)   //有一个来电，挂断，继续判断
                {
                    readBuffer = "";
                    getModemDriver().write("ATH\r");
                }
                //else if (readBuffer.IndexOf("OK") != -1)     //如果当前没有电话在工作，结束判断，无效号码
                //{
                //    readBuffer = "";
                //    break;
                //}
                else if ((readBuffer.IndexOf("NO CARRIER") != -1) || (readBuffer.IndexOf("ERROR") != -1))
                {
                    //始终没有等到振铃，号码无效，结束判断
                    break;
                }

            }

            getModemDriver().write("ATH\r");
            getModemDriver().clearBuffer();
            //ATH 呼叫挂起

            return isSucc;
        }

    }

}